//
//  LGSinaShare.m
//  ShareDemo
//
//  Created by Li Zhiping on 13-11-21.
//  Copyright (c) 2013年 Li Zhiping. All rights reserved.
//

#import "LGSinaShare.h"
#import "LGSinaAccount.h"

@interface LGSinaShare ()<WeiboSDKDelegate, WBHttpRequestDelegate>

//请求用户列表返回操作
@property (assign, nonatomic)LGFriendsResultEvent friendsResultBlock;
    
//分享微博返回操作
@property (assign, nonatomic)LGShareResultEvent shareResultBlock;
    
//标记当前请求, 请求完成回调时使用.
@property (assign, nonatomic)LGWBHttpRequestType httpRequestType;

@property (strong, nonatomic)LGFriendsContent *friendsContent;

@property (strong, nonatomic)LGShareContent *shareContent;

@property (strong, nonatomic)LGSinaAccount *sinaAccount;

@property (copy, nonatomic) NSString *redirectURI;

@end

@implementation LGSinaShare

+ (LGSinaShare *)sharedInstance
{
    static dispatch_once_t pred = 0;
    __strong static LGSinaShare *_sharedObject = nil;
    dispatch_once(&pred, ^{
        _sharedObject = [[self alloc] init];
        [_sharedObject loadDataFromDisk];
    });
    return _sharedObject;
}

+ (NSString *)accessToken{
    LGSinaShare *sinaShare = [self sharedInstance];
    NSString *accessToken = [[sinaShare sinaAccount] accessToken];
    return accessToken;
}

+ (NSString *)authorUid{
    LGSinaShare *sinaShare = [self sharedInstance];
    NSString *authorUid = [[sinaShare sinaAccount] authorUid];
    return authorUid;
}

+ (void)registerApp:(NSString *)appKey
        redirectURI:(NSString *)url{
    LGSinaShare *sinaShare = [self sharedInstance];
    [WeiboSDK registerApp:appKey];
    sinaShare.redirectURI = url;
}

+ (BOOL)isSinaAuthored{
    LGSinaShare *sinaShare = [self sharedInstance];
    NSString *accessToken = [[sinaShare sinaAccount] accessToken];
    return accessToken!=nil;
}

+ (void)logout{
    LGSinaShare *sinaShare = [self sharedInstance];
    sinaShare.httpRequestType = LGWBHttpRequestLogout;
    [WeiboSDK logOutWithToken:[self accessToken] delegate:[self sharedInstance]];
}

+ (void)author{
    LGSinaShare *sinaShare = [self sharedInstance];
    WBAuthorizeRequest *request = [WBAuthorizeRequest request];
    request.redirectURI = sinaShare.redirectURI;
    request.scope = @"all";
    request.userInfo = nil;
    [WeiboSDK sendRequest:request];
}

+ (void)shareContent:(LGShareContent *)content complete:(LGShareResultEvent)complete{
    
    //判断是否授权
    if (![self isSinaAuthored]) {
        [self author];
        return;
    }
    
    LGSinaShare *sinaShare = [self sharedInstance];
    sinaShare.shareResultBlock = complete;
    sinaShare.shareContent = content;
    sinaShare.httpRequestType = LGWBHttpRequestShare;
    
    NSString *accessToken = [[sinaShare sinaAccount] accessToken];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    UIImage *image = content.image;
    
    //发布一条微博信息, 只上传文字
    NSString *reqUrl = @"https://upload.api.weibo.com/2/statuses/update.json";
    
    //如果有添加图片, 则使用上传图片并发布微博接口
    if (image) {
        //上传图片并发布一条微博
        reqUrl = @"https://upload.api.weibo.com/2/statuses/upload.json";
        NSData *picData = UIImagePNGRepresentation(image);
        [params setObject:picData forKey:@"pic"];
    }
    
    NSString *contentStr = content.content;
    if (contentStr) {
        [params setObject:contentStr forKey:@"status"];
    }
    
    //发送微博请求
    [WBHttpRequest requestWithAccessToken:accessToken
                                      url:reqUrl
                               httpMethod:@"POST"
                                   params:params
                                 delegate:sinaShare];
}

+ (void)shareWithWeiboClient:(LGShareContent *)content complete:(LGShareResultEvent)complete{
    WBMessageObject *message = [WBMessageObject message];
    message.text = content.content;
    
    WBImageObject *image = [WBImageObject object];
    image.imageData = UIImagePNGRepresentation(content.image);
    message.imageObject = image;
    
    WBWebpageObject *webpage = [WBWebpageObject object];
    webpage.webpageUrl = content.url;
    message.mediaObject = webpage;
    
    WBSendMessageToWeiboRequest *request = [WBSendMessageToWeiboRequest requestWithMessage:message];
    request.userInfo = content.userInfo;
    [WeiboSDK sendRequest:request];
    
    LGSinaShare *sinaShare = [LGSinaShare sharedInstance];
    sinaShare.shareResultBlock = complete;
    sinaShare.shareContent = content;
}

+ (void)fetchFriendShip:(LGFriendsContent *)content complete:(LGFriendsResultEvent)complete{
    //判断是否授权
    if (![self isSinaAuthored]) {
        [self author];
        return;
    }
    
    LGSinaShare *sinaShare = [LGSinaShare sharedInstance];
    sinaShare.friendsResultBlock = complete;
    sinaShare.friendsContent = content;
    sinaShare.httpRequestType = LGWBHttpRequestFriends;
    
    NSString *friends = @"https://api.weibo.com/2/friendships/friends.json";
    NSString *accessToken = [self accessToken];
    NSString *uid = [self authorUid];
    NSString *count = [NSString stringWithFormat:@"%i", content.count];
    NSString *cursor = [NSString stringWithFormat:@"%i", content.cursor];
    NSDictionary *params = @{@"uid":uid, @"count":count, @"cursor":cursor};
    [WBHttpRequest requestWithAccessToken:accessToken
                                      url:friends
                               httpMethod:@"GET"
                                   params:params
                                 delegate:[self sharedInstance]];
}

+ (BOOL)handleOpenURL:(NSURL *)url{
    [WeiboSDK handleOpenURL:url delegate:[self sharedInstance]];
    return YES;
}

#pragma mark - WeiboSDKDelegate

- (void)didReceiveWeiboRequest:(WBBaseRequest *)request{
    
}

/**
 收到一个来自微博客户端程序的响应
 
 收到微博的响应后，第三方应用可以通过响应类型、响应的数据和 WBBaseResponse.userInfo 中的数据完成自己的功能
 @param response 具体的响应对象
 */
- (void)didReceiveWeiboResponse:(WBBaseResponse *)response{
    if ([response isKindOfClass:WBSendMessageToWeiboResponse.class])
    {
        /*
         *通过微博客户端分享微博时回调方法
         */
    }else if ([response isKindOfClass:WBAuthorizeResponse.class]){
        
        if (response.statusCode == WeiboSDKResponseStatusCodeSuccess) {
            [self.sinaAccount setAccessToken:[(WBAuthorizeResponse *)response accessToken]];
            [self.sinaAccount setAuthorUid:[(WBAuthorizeResponse *)response userID]];
            
            //授权成功, 保存数据
            [self saveDataToDisk];
        }
    }
}

#pragma mark - WBHttpRequestDelegate

- (void)request:(WBHttpRequest *)request didReceiveResponse:(NSURLResponse *)response{
    
}

- (void)request:(WBHttpRequest *)request didFinishLoadingWithResult:(NSString *)result
{
    if (self.httpRequestType == LGWBHttpRequestShare) {
        [self parseShareResult:result error:nil];
    }else if(self.httpRequestType == LGWBHttpRequestFriends){
        [self parseFriendResult:result error:nil];
    }else if (self.httpRequestType == LGWBHttpRequestLogout){
        [self clearAccessToken];
    }
}

- (void)request:(WBHttpRequest *)request didFailWithError:(NSError *)error;
{
    if (self.httpRequestType == LGWBHttpRequestShare) {
        [self parseShareResult:nil error:error];
    }else if(self.httpRequestType == LGWBHttpRequestFriends){
        [self parseFriendResult:nil error:error];
    }else if (self.httpRequestType == LGWBHttpRequestLogout){
        
    }
}

/*
 *解析分享微博后返回的数据
 */
- (void)parseShareResult:(NSString *)result error:(NSError *)error{
    if (!error) {
        NSData *jsonData = [result dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:jsonData  options:NSJSONReadingAllowFragments error:nil];
        NSString *error_code = resultDic[@"error_code"];
        LGErrorInfo *errorInfo = nil;
        LGResponseState state = LGResponseStateSuccess;
        if (error_code) {
            errorInfo.errorCode = [error_code integerValue];
            errorInfo.errorDescription = resultDic[@"error"];
            errorInfo.errorLevel = LGErrorLevelAPI;
            state = LGResponseStateFail;
        }
        _shareResultBlock(state, _shareContent, errorInfo);
    }
}

/*
 *解析获取到的用户列表数据
 */
- (void)parseFriendResult:(NSString *)result error:(NSError *)error{
    if (!error) {
        NSData *jsonData = [result dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:jsonData  options:NSJSONReadingAllowFragments error:nil];
        NSString *error_code = resultDic[@"error_code"];
        LGErrorInfo *errorInfo = nil;
        if (error_code) {
            errorInfo.errorCode = [error_code integerValue];
            errorInfo.errorDescription = resultDic[@"error"];
            errorInfo.errorLevel = LGErrorLevelAPI;
        }
        
        NSArray *users = [resultDic objectForKey:@"users"];
        long long prev = [[resultDic objectForKey:@"previous_cursor"] longLongValue];
        long long next = [[resultDic objectForKey:@"next_cursor"] longLongValue];
        long long total_number = [[resultDic objectForKey:@"total_number"] longLongValue];
        
        BOOL hasNext = next == total_number;
        long long curr = self.friendsContent.cursor;
        
        _friendsResultBlock(LGResponseStateSuccess, users, curr, prev, next, hasNext, nil, errorInfo);
    }
}

#pragma mark - private

//保存数据到文件中
- (void)saveDataToDisk{
    NSData *archiveCarPriceData = [NSKeyedArchiver archivedDataWithRootObject:self.sinaAccount];
    [[NSUserDefaults standardUserDefaults] setObject:archiveCarPriceData forKey:@"sinaAccount"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

//从文件中加载数据
- (LGSinaAccount *)loadDataFromDisk{
    NSData *accountData = [[NSUserDefaults standardUserDefaults] objectForKey:@"sinaAccount"];
    LGSinaAccount *account = [NSKeyedUnarchiver unarchiveObjectWithData: accountData];
    if (!account) {
        account = [[LGSinaAccount alloc] init];
    }
    self.sinaAccount = account;
    return account;
}

- (void)clearAccessToken{
    //清空内存中数据
    [self.sinaAccount setAccessToken:nil];
    [self.sinaAccount setAuthorUid:nil];
    
    //清空保存在文件中的数据
    [self saveDataToDisk];
}

@end
